package cn.thornbird.orgsync.config;

import cn.thornbird.orgsync.model.UserData;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class AuditorConfig implements AuditorAware<String> {

    @Override
    public Optional<String> getCurrentAuditor() {
        Optional<String> auditor = Optional.of("system");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
            UserData userData = (UserData) authentication.getPrincipal();
            if (userData != null && userData.getUsername() != null) {
                auditor = Optional.of(userData.getUsername());
            }
        }
        return auditor;
    }

}
